<template>
  <div class="pagination">
    <button :disabled="curPage === 1" @click="changeCurrentPage(curPage - 1)">
      上一页
    </button>
    <button v-show="start > 1" @click="changeCurrentPage(1)">1</button>
    <button v-show="start > 2" style="cursor: unset">···</button>

    <template v-for="(item, index) in end">
      <button
        :class="{ active: curPage === index + 1 }"
        v-if="start <= item"
        :key="index"
        @click="changeCurrentPage(item)"
      >
        {{ item }}
      </button>
    </template>

    <button v-show="end < pageTotalNum - 1" style="cursor: unset">···</button>
    <button
      v-show="end !== pageTotalNum"
      @click="changeCurrentPage(pageTotalNum)"
    >
      {{ pageTotalNum }}
    </button>
    <button
      :disabled="curPage === pageTotalNum"
      @click="changeCurrentPage(curPage + 1)"
    >
      下一页
    </button>

    <span>共{{ total }}条</span>
  </div>
</template>

<script>
export default {
  name: 'Pagination',
  props: {
    // 商品总数量
    total: {
      type: Number,
      default: 0
    },
    // 当前页
    curPage: {
      type: Number,
      default: 1
    },
    // 每页大小
    pageSize: {
      type: Number,
      default: 10
    }
  },
  methods: {
    changeCurrentPage (curPage) {
      if (this.curPage === curPage) {
        return ''
      }
      this.$emit('current-page', curPage)
    }
  },
  computed: {
    // 总页码数
    pageTotalNum () {
      return Math.ceil(this.total / this.pageSize)
    },
    // 当前页码的前2位
    start () {
      // 当前页码小于3,左右不对称,start直接为1
      if (this.curPage < 3) {
        return 1
      } else {
        return this.curPage - 2
      }
    },
    // 当前页码的后2位
    end () {
      // 当前页码不能大于总页码-2
      if (this.curPage > this.pageTotalNum - 2) {
        return this.pageTotalNum
      } else {
        return this.curPage + 2
      }
    }
  }
}
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  span,
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }
  }

  span {
    cursor: none !important;
    background-color: unset !important;
  }
  .active {
    background-color: #409eff;
    color: #fff;
    cursor: unset;
  }
}
</style>
